package logic

import (
	"context"
	"fmt"
	"selection-inventory/application/applet/internal/model"
	"selection-inventory/application/applet/internal/svc"
	"selection-inventory/application/applet/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetCommodityListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCommodityListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCommodityListLogic {
	return &GetCommodityListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetCommodityListLogic) GetCommodityList(req *types.ListRequest) (resp *types.ListResponse, err error) {
	var commodityList []*model.Commodity
	var total int64
	sql := l.svcCtx.DB.Model(&model.Commodity{}).
		Where("deleted_at IS NULL").
		Order("id desc")
	if req.Id != 0 {
		sql = sql.Where("id = ?", req.Id)
	}
	if req.Title != "" {
		sql = sql.Where("title LIKE ?", "%"+req.Title+"%")
	}
	if req.Ali != "" {
		sql = sql.Where("ali LIKE ?", "%"+req.Ali+"%")
	}
	if req.Pdd != "" {
		sql = sql.Where("pdd LIKE ?", "%"+req.Pdd+"%")
	}
	if req.Douyin != "" {
		sql = sql.Where("douyin LIKE ?", "%"+req.Douyin+"%")
	}
	if req.Taobao != "" {
		sql = sql.Where("taobao LIKE ?", "%"+req.Taobao+"%")
	}
	result := sql.Count(&total)
	if result.Error != nil {
		return
	}
	res := sql.Limit(req.Size).Offset((req.Page - 1) * req.Size).Find(&commodityList)
	if res.Error != nil {
		fmt.Println(res.Error.Error())
		return
	}
	var list []types.UpdateRequest

	for _, commodity := range commodityList {
		updateRequest := types.UpdateRequest{
			Id:      commodity.Id,
			Title:   commodity.Title,
			Picture: commodity.Picture,
			Ali:     commodity.Ali,
			Douyin:  commodity.Douyin,
			Pdd:     commodity.Pdd,
			Taobao:  commodity.Taobao,
		}
		list = append(list, updateRequest)
	}
	return &types.ListResponse{
		Total: total,
		List:  list,
	}, nil
}
